package com.jf.game

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.github.salomonbrys.kotson.fromJson
import com.github.salomonbrys.kotson.jsonObject
import com.google.gson.JsonElement
import com.helloandroid.AppUtil
import com.helloandroid.app.model.AppCache
import com.helloandroid.ext.Json
import com.helloandroid.ext.parseJFInfo
import com.helloandroid.ext.process
import com.helloandroid.tools.AppConfig
import com.helloandroid.tools.GUtils
import com.helloandroid.tools.Http.asyncHttpReq
import com.helloandroid.tools.MyLog
import com.helloandroid.tools.NetWorkUtil
import com.helloandroid.vo.IDeepCopy
import dai.common.util.CommonUtils
import kotlinx.coroutines.*
import org.json.JSONObject
import java.lang.RuntimeException


data class JFResult(val result_id:Int,val count:Int)
data class JFInfo(var fu:Int,var lu:Int,var shou:Int,var xi:Int,var cai:Int,var restcount:Int):IDeepCopy<JFInfo>{
    fun increase(ret: JFResult){
        when(ret.result_id){
            JFViewModel.Fu -> fu += ret.count
            JFViewModel.Lu -> lu += ret.count
            JFViewModel.Shou -> shou += ret.count
            JFViewModel.Xi -> xi += ret.count
            JFViewModel.Cai -> cai += ret.count
            JFViewModel.Coin -> AppUtil.increaseCoin(ret.count)
            else -> throw RuntimeException("unknow result_id:${ret.result_id}")
        }
    }

    override fun deepCopy(): JFInfo {
        return this.copy()
    }

    fun kaCount():Int{
        return  fu + lu + shou + cai + xi
    }

    // 卡种类的个数
    fun kaTypeCount():Int{
        var typeCount = 0
        if (fu > 0){
            typeCount++
        }
        if (lu > 0){
            typeCount++
        }
        if (shou > 0){
            typeCount++
        }
        if (xi > 0){
            typeCount++
        }
        if (cai > 0){
            typeCount++
        }
        return  typeCount
    }

    // 产生第4种卡类型
    fun genFourthKaType():Int{
        var arr = ArrayList<Int>()
        if (fu < 1){
            arr.add(JFViewModel.Fu)
        }
        if (lu < 1){
            arr.add(JFViewModel.Lu)
        }
        if (shou < 1){
            arr.add(JFViewModel.Shou)
        }
        if (xi < 1){
            arr.add(JFViewModel.Xi)
        }
        if (cai < 1){
            arr.add(JFViewModel.Cai)
        }
        return arr[CommonUtils.randomInt(0,arr.size - 1)]
    }

    // 产生一个非关键类型的卡
    fun genNotKeyKaType():Int{
        var arr = ArrayList<Int>()
        if (fu > 0){
            arr.add(JFViewModel.Fu)
        }
        if (lu > 0){
            arr.add(JFViewModel.Lu)
        }
        if (shou > 0){
            arr.add(JFViewModel.Shou)
        }
        if (xi > 0){
            arr.add(JFViewModel.Xi)
        }
        if (cai > 0){
            arr.add(JFViewModel.Cai)
        }

        // 从存在的这里面挑一个
        if (arr.contains(JFViewModel.Lu)){
            val n = CommonUtils.randomInt(0,8)
            if (n >= 3){
                return JFViewModel.Lu
            }else{
                return arr[CommonUtils.randomInt(0,arr.size-1)]
            }
        }else{
            return arr[CommonUtils.randomInt(0,arr.size-1)]
        }
    }
}


class JFViewModel:ViewModel() {

    var rolling = false

    companion object{
        // 表示 抽奖结果Id
        const val Fu = 1
        const val Lu = 2
        const val Shou = 3
        const val Xi = 4
        const val Cai = 5
        const val Coin = 6

        const val BigCoin = 68
        const val MidCoin = 58
        const val SmallCoin = 48
    }

    fun getInfo(callback:(Boolean,JFInfo?)->Unit){

        val info = AppCache.copyJFInfo()
        if (info != null){
            callback(true,info)
            return
        }

        if (!NetWorkUtil.networkConnected()){
            AppUtil.toast("请打卡网络!")
            callback(false,null)
            return
        }

        viewModelScope.launch {
//            val defer = async(Dispatchers.IO){
//                httpGetInfo()
//            }
//            val jsonStr = defer.await()
//            MyLog.info("服务端返回:$jsonStr")
//            val jsonObj = JSONObject(jsonStr)
            val url = "game/niudan/info?user_id=${AppUtil.user.user_id}"
            val jsonObj = JSONObject(asyncHttpReq(url))
            val parseResult = jsonObj.process(JSONObject::parseJFInfo)
            if(parseResult.err == 0){
                val info = parseResult.obj as JFInfo
                AppCache.jfInfo = info
                callback(true,AppCache.copyJFInfo())
            }else{
                MyLog.info("err:${parseResult.err},msg:${parseResult.msg}")
                callback(false,null)
            }
        }
    }

//    private suspend fun httpGetInfo():String{
//        NetWorkUtil.mockDelay()
//        return Json{
//            "err" to 0
//            "data" to Json{
//                "fu" to 0
//                "lu" to 0
//                "shou" to 0
//                "cai" to 0
//                "xi" to 0
//                "restcount" to 10
//            }
//        }.toString()
//    }

    fun randomKaType():Int{
        return CommonUtils.randomInt(Fu, Cai)
    }

    fun roll(action:()->Boolean,callback:()->Unit){

        if (rolling){
            MyLog.info("already rolling, maybe error!")
            return
        }

        rolling = true
        viewModelScope.launch {
            while (isActive && rolling){
                delay(100)
                if (action.invoke()){
                    rolling = false
                    callback()
                    break
                }
            }
        }
    }

    override fun onCleared() {
        rolling = false
        super.onCleared()
    }
}